/**
 * 用户管理模块
 */
const router = require('koa-router')()
const bodyparser = require('koa-bodyparser')
// const { user } = require('../config');
const util = require('../utils/util')
const jwt = require('jsonwebtoken')
const { PRIVATE_KEY, JWT_EXPIRED } = require('../utils/constant')
const jwtAuth = require('./jwt')
const { query } = require('../config/db');
const path = require('path')

//调用中间件，拿到前端post数据
router.use(bodyparser());

router.use(jwtAuth)
// router.prefix('/users')
// 登录
router.post('/login', async (ctx) => {
  try {
    console.log(ctx, 123);
    const { username, password } = ctx.request.body;
    const res = await util.login(username, password);
    console.log(res, 0);
    if (res && res.length) {
      const token = util.creatToken(res)
      // res.token = token;
      console.log(res, 1);
      ctx.body = util.success(res[0], token);
    } else {
      ctx.body = util.error('账号或密码不正确');
    }
  } catch (error) {
    console.log('cuowu ');
    ctx.body = util.fail(error);
  }
})

// 注册
router.post('/register', async (ctx) => {
  try {
    const { username, phone, email, password, portrait, role = 0 } = ctx.request.body;
    const sql = `insert into users (username, phone, email, password, portrait, role) values('${username}', '${phone}', '${email}', '${password}', '${portrait}', '${role}')`;
    await query(sql);
    ctx.body = util.success('注册成功');
  } catch (error) {
    console.log(error, 3);
    ctx.body = util.fail(error);
  }
})

router.post('/getImgPath', async (ctx) => {
  try {
    // console.log(ctx.request.files.file);
    const file = ctx.request.files.file   //  ctx.request.files.file中的file需要与前端使用的名称保持一致
    // console.log(file.filepath);
    const basename = path.basename(file.filepath) //传入绝对路径返回的basename为文件名称+拓展名
    ctx.body = util.success({ url: `${ctx.origin}/uploads/${basename}` })
    // const res = await section(sid)
    // console.log(res);
    // ctx.body = util.success(res)
  } catch (error) {
    console.log(error);
    ctx.body = util.fail(error);
  }
})

// 自动登录
router.post('/', async (ctx) => {
  try {
    const { token } = ctx.request.body;
    const decoded = util.decoded(token);
    console.log(decoded, 123);
    if (decoded && decoded.res) {
      // token = jwt.sign(
      //   decode.res[0],
      //   PRIVATE_KEY,
      //   { expiresIn: JWT_EXPIRED }
      // )
      const res = await util.login(decoded.res[0].username, decoded.res[0].password)
      const newToken = util.creatToken(res);
      ctx.body = util.success(decoded.res[0], newToken)
    }
  } catch (error) {
    ctx.body = util.fail(error);
  }
})

// 更改密码
router.post('/center/updatePwd', async (ctx) => {
  try {
    const {
      username,
      oldPwd,
      newPwd,
      token
    } = ctx.request.body;
    util.decoded(token);
    const sql = `update users set password = '${newPwd}'  where username = '${username}' and password = '${oldPwd}'`;
    await query(sql);
    const res = await util.login(username, newPwd)
    const newToken = util.creatToken(res);
    ctx.body = util.success(res[0], newToken, '修改成功');
  } catch (error) {
    console.log(error, 3);
    ctx.body = util.fail(error);
  }
})
// 更改我的信息
router.post('/center/updateInfo', async (ctx) => {
  try {
    const {
      username,
      phone,
      email,
      introduction,
      token
    } = ctx.request.body;

    // 验证token
    const decoded = util.decoded(token);
    console.log(decoded);
    const sql = `update users set username = '${username}',phone='${phone}',email='${email}',introduction='${introduction}'  where username = '${decoded.res[0].username}' and password = '${decoded.res[0].password}'`;
    await query(sql);
    const res = await util.login(username, decoded.res[0].password)
    const newToken = util.creatToken(res);
    ctx.body = util.success(res[0], newToken, '更新成功');
  } catch (error) {
    console.log(error, 3);
    ctx.body = util.fail(error);
  }
})

//上传图片
router.post('/getImgPath', (ctx) => {
  const res = ctx.request;
  console.log(res);
})



// router.post('/login', async (ctx) => {
//   console.log(ctx.request.body, 123);
//   const { userName, userPwd } = ctx.request.body;

//   const res = await util.searchUser(userName, userPwd);
//   console.log(res, 456);
//   if (res) {
//     console.log(res, 111);
//     ctx.body = util.success(res, 11);
//   } else {
//     console.log(222);
//     ctx.body = util.fail('账号或密码不正确');
//   }
// })

// router.use((err, req, res, next) => {
//   console.log(1);
//   console.log(err, 111)
//   const msg = (err && err.message) || '系统错误'
//   const statusCode = (err.output && err.output.statusCode) || 500;
//   const errorMsg = (err.output && err.output.payload && err.output.payload.error) || err.message
//   res.status(statusCode).json({
//     code: CODE_ERROR,
//     msg,
//     error: statusCode,
//     errorMsg
//   })
// })


module.exports = router
